package persistance;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;

import domain.DomainObject;

import usuario.Usuario;

public class DomainDAO {
	
	private static SessionFactory sessionFactory;
	protected static Session session;
	
	static{
		if (sessionFactory == null){
			sessionFactory = new Configuration().configure().buildSessionFactory();
			session = sessionFactory.openSession();
		}
	}
	
	public static void save(Object object){
		Transaction tx = session.beginTransaction();
		session.save(object);
		tx.commit();
	}
	
	public static void saveOrUpdate(Object object){
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(object);
		tx.commit();
	}

	public static void delete(DomainObject object){
		Transaction tx = session.beginTransaction();
		object.setEstado("BA");
		session.update(object);
		tx.commit();
	}

	public static Object getById(Long id, Class clazz){
		Object ob = session.get(clazz, id);
		return ob;
	}
	
	@SuppressWarnings("unchecked")
	public static List<?> getByIdEmpresa(Long idEmpresa, Class clazz){
		Criteria criteria = session.createCriteria(clazz).add(Restrictions.eq("idEmpresa", idEmpresa));
		criteria.add(Restrictions.eq("estado", "OP"));
		List<?> lista = criteria.list();
		if (lista == null){
			lista = new ArrayList();
		}
		return lista;
	}
	
	@SuppressWarnings("unchecked")
	public static List<?> getByProperty(String propName, Object value, Long idEmpresa, Class clazz){
		Criteria criteria = session.createCriteria(clazz).add(Restrictions.eq(propName, value));
		criteria.add(Restrictions.eq("estado", "OP"));
		criteria.add(Restrictions.eq("idEmpresa", idEmpresa));
		List<?> lista = criteria.list();
		if (lista == null){
			lista = new ArrayList();
		}
		return lista;
		
	}
}
